import 'package:flutter/cupertino.dart';
import 'package:get_storage/get_storage.dart';

///为了降低 各组件的Controller之间的耦合度,采用将数据写入内存,同时监听的方式来做事件通知
class StorageService {
  GetStorage? _storage;

  factory StorageService() => _getInstance();

  static StorageService get instance => _getInstance();
  static StorageService? _instance;

  static StorageService _getInstance() {
    if (_instance == null) {
      _instance = StorageService._internal();
    }
    return _instance!;
  }

  StorageService._internal() {
    _storage = GetStorage('im_base');
  }

  ///将数据写入内存中
  void writeData(String key, dynamic data) async {
    await _storage?.write(key, data);
  }

  ///从内存中读取数据
  T? readData<T>(String key) {
    return _storage?.read<T>(key);
  }

  void watchData(String key, Function(dynamic) callBack) {
    _storage?.listenKey(key, callBack);
  }

  ///移除监听器集合
  void removeListenerList(Set<ValueSetter> listeners) {
    _storage?.removeListenerList(listeners);
  }

  ///擦除数据,因为在内存中所以每次app退出都会自动擦除
  ///但是如果用户退出登录需要手动调用擦除数据
  void eraseData() async {
    await _storage?.erase();
  }

  ///退出登录统一方法
  void logout() {
    eraseData();
  }
}
